package com.hcc.gateway.app.filter;

import com.hcc.gateway.netty.context.GatewayExchange;
import com.hcc.gateway.netty.context.ReqContext;
import com.hcc.gateway.netty.filter.GatewayFilter;
import com.hcc.gateway.netty.filter.GatewayFilterChain;
import com.hcc.gateway.netty.route.GatewayRoute;
import com.hcc.gateway.netty.support.GatewayConstants;
import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.URI;

/**
 * RouteToRequestUrlFilter
 *
 * @author shengjun.hu
 * @date 2021/12/28
 */
@Slf4j
@Component("appRouteToReqUrlFilter")
public class RouteToReqUrlFilter implements GatewayFilter {

    @Override
    public int getOrder() {
        return 200;
    }

    @Override
    public void filter(GatewayExchange exchange, GatewayFilterChain chain) {
        log.info("进入RouteToRequestUrlFilter !");
        GatewayRoute route = exchange.getAttributeByName(GatewayConstants.GATEWAY_ROUTE_ATTR, GatewayRoute.class);
        if (route == null) {
            exchange.getRespContext().setHttpStatus(HttpResponseStatus.NOT_FOUND);
            return;
        }

        URI uri = route.getUri();
        ReqContext reqContext = exchange.getReqContext();
        String originalUri = reqContext.getOriginalUri();

        String query = "";
        if (originalUri.contains("?")) {
            query = originalUri.substring(originalUri.indexOf("?"));
        }
        URI mergeUri = URI.create(uri.toString() + query);

        exchange.addAttribute(GatewayConstants.GATEWAY_REQUEST_URI_ATTR, mergeUri);

        chain.filter(exchange);
    }

}
